package com.simple.demo.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.*;


public class NioServer {


    public static void main(String[] args) {
        try {
            ThreadPoolExecutor threadPool =
                    new ThreadPoolExecutor(4, 4,
                            60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
            Selector selector = Selector.open();
            ServerSocketChannel  socketChannel = ServerSocketChannel.open();
            socketChannel.configureBlocking(false);
            socketChannel.bind(new InetSocketAddress(5000));
            socketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("server is starting on 5000...");
            while (selector.select() > 0 ){
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> selectItor = selectionKeys.iterator();
                while(selectItor.hasNext()){
                    SelectionKey  selectionKey = selectItor.next();
                    if(selectionKey.isAcceptable()){
                        SocketChannel sc = socketChannel.accept();
                        if(sc != null){
                            threadPool.submit(new Thread(()->{
                             //提交一个线程去处理
                                execute(sc);
                            }));
                        }

                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void execute(SocketChannel sc ){

        ByteBuffer buff = ByteBuffer.allocate(50);
        boolean flag = true;
        try {
        while(flag){

            buff.clear();
            int read = sc.read(buff);
            String readMsg = new String(buff.array(),0,read);
            System.out.println(" recive client  msg is:"+readMsg);
            String writeMsg = "hello,"+readMsg;
            if(readMsg.equals("bye")){
                flag = false;
                writeMsg = "[Exit] byebye" + "\n";
            }
            //回写数据
            buff.clear();
            buff.put(writeMsg.getBytes());
            // 重置缓冲区让其输出
            buff.flip();
            sc.write(buff);
        }
        sc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
